package com.lx.iccp.activity.app.logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.google.common.base.Strings;
import com.lx.iccp.support.api.logger.Log;
import com.lx.iccp.support.api.model.auto.IccpSystemOperLog;
import com.lx.iccp.support.api.service.OperLogService;
import com.lx.iccp.support.common.enums.ValidCodeEnum;
import com.lx.iccp.support.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 操作日志记录处理
 * 
 * @author kaiyuan
 */
@Aspect
@Component
@Slf4j
public class LogAspect
{
    @DubboReference
    OperLogService asyncOperService;

    /** 排除敏感属性字段 */
    protected static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };

    /**
     * 配置织入点
      */
    @Pointcut("@annotation(com.lx.iccp.support.api.logger.Log)")
    public void logPointCut()
    {
        // Do nothing because of X and Y.
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
    {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
    {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
    {
        try
        {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null)
            {
                return;
            }
            // 获取当前的用户
            String userId = ServletUtils.getRequest().getHeader("x-auth-userId");
            String userType = ServletUtils.getRequest().getHeader("x-auth-userType");

            // *========数据库日志=========*//
            IccpSystemOperLog operLog = new IccpSystemOperLog();
            operLog.setOperStatus(ValidCodeEnum.VALID.getCode());
            // 请求的地址
            String ip = ServletUtils.getRequest().getHeader("x-real-ip");
            if (Strings.isNullOrEmpty(ip)) {
                ip = ServletUtils.getRequest().getRemoteHost();
            }
            operLog.setOperIp(ip);
            // 返回参数
            operLog.setJsonResult(JSON.toJSONString(jsonResult));
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
            operLog.setOperUserId(userId);
            operLog.setOperUserType(userType);

            if (e != null)
            {
                operLog.setOperStatus(ValidCodeEnum.INVALID.getCode());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, operLog);
            operLog.setOperPost(JSON.toJSONString(joinPoint.getArgs()));
            operLog.setOperTime(new Date());

            new Thread((new Runnable() {
                @Override
                public void run() {
                    // 批量同步数据
                    try {
                        // 保存数据库
                        asyncOperService.recordOper(operLog);
                    } catch (Exception e) {
                        log.error("asyncOperService.recordOper error e={}", e);
                    }
                }
            })).start();
        }
        catch (Exception exp)
        {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log 日志
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(Log log, IccpSystemOperLog operLog)
    {
        // 设置action动作
        operLog.setBusinessType(log.businessType().getType());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperUserType(log.userType().getUserType());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData())
        {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(operLog);
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(IccpSystemOperLog operLog)
    {
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        if (!Objects.isNull(map))
        {
            PropertyPreFilters.MySimplePropertyPreFilter excludefilter = new PropertyPreFilters().addFilter();
            excludefilter.addExcludes(EXCLUDE_PROPERTIES);
            String params = JSON.toJSONString(map, excludefilter);
            operLog.setOperParam(params);
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint)
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}
